# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     preict
   Description :
   Author :       Flyoung
   date：          2023/9/5
-------------------------------------------------
   Change Activity:
                   2023/9/5:
-------------------------------------------------
"""
import json
import os
import numpy as np
import torch
import analyse
from analyse.score_model.model import EvaluateNet


def load_model(pth_path_, std_path_):
    model_ = EvaluateNet()
    model_.load_state_dict(torch.load(pth_path_))
    with open(std_path_, mode='r', encoding='utf8') as f:
        std_args_ = json.load(f).get('stand')
    return model_, std_args_


def predict(model_, std_args_, x):
    x = (x - np.array(std_args_.get('mean'))) / np.array(std_args_.get('std'))
    x = torch.tensor(x, dtype=torch.float)
    return round(model_(x).item(), 2)


def predict_web(request_data):
    field_list = [
        "city_score",
        "education_score",
        "tech_score",
        "welfare_score",
        "salary_upper_limit",
        "salary_lower_limit",
        "experience_upper_limit",
        "experience_lower_limit",
        "company_size_upper_limit",
        "company_size_lower_limit"
    ]
    x = list()
    for field in field_list:
        if field in request_data:
            x.append(request_data[field])
        else:
            x.append(0)
    model_dir = os.path.dirname(analyse.__file__)
    pth_path = os.path.join(model_dir, "../check_point/eval_net.pth")
    std_path = os.path.join(model_dir, "../check_point/eval_net.json")
    model, std_args = load_model(pth_path, std_path)
    y = predict(model, std_args, np.array(x))
    return y
